package com.example.project7;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.example.project7.adapter.BookAdapter;
import com.example.project7.database.BookDatabase;
import com.example.project7.model.Book;
import java.util.List;

public class BookManagerActivity extends AppCompatActivity {
    private TextInputEditText etBookNumber;
    private TextInputEditText etBookName;
    private Button btnAdd;
    private Button btnDelete;
    private Button btnUpdate;
    private Button btnSearch;
    private RecyclerView recyclerView;
    private BookAdapter bookAdapter;
    
    private BookDatabase bookDatabase;
    private String currentUserEmail;
    private Book selectedBook; // 当前选中的书籍，用于编辑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        
        // 获取传递的用户邮箱
        currentUserEmail = getIntent().getStringExtra("user_email");
        if (TextUtils.isEmpty(currentUserEmail)) {
            Toast.makeText(this, "用户信息错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 初始化数据库
        bookDatabase = new BookDatabase(this);
        
        // 初始化控件
        initViews();
        
        // 初始化RecyclerView
        initRecyclerView();
        
        // 设置点击事件
        setupClickListeners();
        
        // 加载初始数据
        loadBooks();
        
        // 设置标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("我的书籍");
        }
    }
    
    /**
     * 初始化控件
     */
    private void initViews() {
        etBookNumber = findViewById(R.id.et_book_number);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnSearch = findViewById(R.id.btn_search);
        recyclerView = findViewById(R.id.recycler_view);
    }
    
    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        bookAdapter = new BookAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(bookAdapter);
        
        // 设置点击事件
        bookAdapter.setOnBookClickListener(new BookAdapter.OnBookClickListener() {
            @Override
            public void onBookClick(int position, Book book) {
                // 选中书籍进行编辑
                selectedBook = book;
                etBookNumber.setText(book.getBookNumber());
                etBookName.setText(book.getBookName());
                Toast.makeText(BookManagerActivity.this, "已选中书籍，可进行修改或删除操作", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置长按事件
        bookAdapter.setOnBookLongClickListener(new BookAdapter.OnBookLongClickListener() {
            @Override
            public boolean onBookLongClick(int position, Book book) {
                // 长按删除书籍
                showDeleteConfirmDialog(book);
                return true;
            }
        });
    }
    
    /**
     * 设置点击事件
     */
    private void setupClickListeners() {
        // 添加按钮
        btnAdd.setOnClickListener(v -> {
            String bookNumber = etBookNumber.getText().toString().trim();
            String bookName = etBookName.getText().toString().trim();
            
            if (TextUtils.isEmpty(bookNumber)) {
                Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (TextUtils.isEmpty(bookName)) {
                Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 创建新书籍
            Book book = new Book();
            book.setBookNumber(bookNumber);
            book.setBookName(bookName);
            book.setUserEmail(currentUserEmail);
            
            // 保存到数据库
            bookDatabase.addBook(book);
            
            // 清空输入框
            etBookNumber.setText("");
            etBookName.setText("");
            selectedBook = null;
            
            // 重新加载数据
            loadBooks();
            
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
        });
        
        // 删除按钮
        btnDelete.setOnClickListener(v -> {
            if (selectedBook == null) {
                Toast.makeText(this, "请先选择要删除的书籍", Toast.LENGTH_SHORT).show();
                return;
            }
            
            showDeleteConfirmDialog(selectedBook);
        });
        
        // 修改按钮
        btnUpdate.setOnClickListener(v -> {
            if (selectedBook == null) {
                Toast.makeText(this, "请先选择要修改的书籍", Toast.LENGTH_SHORT).show();
                return;
            }
            
            String bookNumber = etBookNumber.getText().toString().trim();
            String bookName = etBookName.getText().toString().trim();
            
            if (TextUtils.isEmpty(bookNumber)) {
                Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (TextUtils.isEmpty(bookName)) {
                Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新书籍信息
            selectedBook.setBookNumber(bookNumber);
            selectedBook.setBookName(bookName);
            
            // 保存到数据库
            bookDatabase.updateBook(selectedBook);
            
            // 清空输入框和选中状态
            etBookNumber.setText("");
            etBookName.setText("");
            selectedBook = null;
            
            // 重新加载数据
            loadBooks();
            
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
        });
        
        // 查询按钮
        btnSearch.setOnClickListener(v -> {
            String query = etBookNumber.getText().toString().trim();
            if (TextUtils.isEmpty(query)) {
                query = etBookName.getText().toString().trim();
            }
            loadBooks(query);
        });
    }
    
    /**
     * 加载书籍数据
     */
    private void loadBooks() {
        loadBooks(null);
    }
    
    /**
     * 根据查询条件加载书籍数据
     * @param query 查询条件
     */
    private void loadBooks(String query) {
        List<Book> books = bookDatabase.searchBooks(currentUserEmail, query);
        bookAdapter.updateData(books);
    }
    
    /**
     * 显示删除确认对话框
     * @param book 要删除的书籍
     */
    private void showDeleteConfirmDialog(Book book) {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除书籍《" + book.getBookName() + "》吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 从数据库删除
                    bookDatabase.deleteBook(book);
                    
                    // 如果删除的是选中的书籍，清空选中状态
                    if (selectedBook != null && selectedBook.getId().equals(book.getId())) {
                        selectedBook = null;
                        etBookNumber.setText("");
                        etBookName.setText("");
                    }
                    
                    // 重新加载数据
                    loadBooks();
                    
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}